package com.datumdroid.android.ocr.simple;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.text.Html;
//import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class XMLDownloadActivity extends AsyncTask<Object, Object, Object>{

   private TextView dataField;
   private TextView queryField;
   private Context context;
   private String qText;
   public XMLDownloadActivity(Context context,TextView dataField, TextView queryField) {
      this.context = context;
      this.dataField = dataField;
      this.queryField = queryField;
   }


   //check Internet conenction.
   private void checkInternetConenction(){
      ConnectivityManager check = (ConnectivityManager) this.context.
      getSystemService(Context.CONNECTIVITY_SERVICE);
      if (check != null) 
      {
         NetworkInfo[] info = check.getAllNetworkInfo();
         if (info != null) 
            for (int i = 0; i <info.length; i++) 
            if (info[i].getState() == NetworkInfo.State.CONNECTED)
            {
               Toast.makeText(context, "Internet is connected",
               Toast.LENGTH_SHORT).show();
            }

      }
      else{
         Toast.makeText(context, "not conencted to internet",
         Toast.LENGTH_SHORT).show();
          }
      
      
      
      
   }
   @Override
   protected void onPreExecute(){
      checkInternetConenction();
      this.qText = queryField.getText().toString();
   }
   

   protected String doInBackground(String... arg0) {
      try{
         String link = (String)arg0[0];
         URL url = new URL(link);
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         conn.setReadTimeout(10000);
         conn.setConnectTimeout(15000);
         conn.setRequestMethod("GET");
         conn.setDoInput(true);
         conn.connect();
         InputStream is = conn.getInputStream();
         BufferedReader reader = new BufferedReader(new InputStreamReader
         (is, "UTF-8") );
         String data = null;
         String webPage = "";
         while ((data = reader.readLine()) != null){
            webPage += data + "\n";
         }
         return webPage;
      }catch(Exception e){
         return new String("Exception: " + e.getMessage());
      }
   }
   

   protected void onPostExecute(Object result){
      this.dataField.setText(Html.fromHtml(result.toString()));
   }


@Override
protected Object doInBackground(Object... arg0) {
    try{
        String link = (String)arg0[0];
        URL url = new URL(link);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader
        (is, "UTF-8") );
        String data = null;
        String webPage = "";
        while ((data = reader.readLine()) != null){
           webPage += data + "\n";
        }
        String result = "";
        
     /*   JSONObject jResponseObj = new JSONObject(webPage);
        JSONObject response = jResponseObj.getJSONObject("response");
        double maxScore = response.getDouble("maxScore");
        JSONArray bTitle = response.getJSONArray("response");
        JSONObject oneBook = bTitle.getJSONObject(2);
        result = result + maxScore + "\n\n";
        result = result + oneBook.getString("title") + "\n\n";*/
        
        JSONObject jObject = new JSONObject(webPage);
        JSONObject responseHeader = jObject.getJSONObject("response");
        int booksFound = responseHeader.getInt("numFound");
        result = result + "<br><b>Books in DB:</b> " + booksFound + "</br>";
        JSONArray bookNames = responseHeader.getJSONArray("docs");
        if (booksFound>0){
        	JSONObject oneBook = bookNames.optJSONObject(booksFound-1);
        	result = result + "<br><b>Books' name:</b> " + oneBook.getString("title") + "</br>";
        	result = result + "<br><b>Books' author:</b> " + oneBook.getString("author") + "</br>";
        	result = result + "<br><b>Books' score:</b> " + oneBook.getString("score") + "</br>";
        }
        JSONObject rHeader = jObject.getJSONObject("highlighting");
        JSONObject params = rHeader.getJSONObject("");
        JSONArray text = params.getJSONArray("text");
        //String  oneObject = text.getString(0);
        result = result + "<br><b>Text snip:</b> " + text.getString(0) + "</br>";
        //JSONObject q = params.getJSONObject("q");
       // JSONArray jArray = rHeader.getJSONArray("text");
        //result = text.getString(0);
        //System.out.println(rHeader);
        //result  = jArray.getJSONObject(1).getString(null);
        /*for (int i=0; i < text.length(); i++)
        {
            try {
            	String  oneObject = text.getString(i);
                // Pulling items from the array
            	result = result + "<br>-------------------------------------------------------------------</br>" + oneObject;
            } catch (JSONException e) {
            	return new String("Exception: " + e.getMessage());
            }
        }*/
        //String QTime = rHeader.getString("QTime");
   		//aJsonString = jObject.getString(qText);
        //String aJsonString = jObject.getString(qText);
        //JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
        
        return result;// + "<br>-------------------------------------------------------------------</br>" + webPage;
     }catch(Exception e){
        return new String("Exception: " + e.getMessage());
     }
}
}